package com.mars.web.rest.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageInfo;
import com.mars.base.common.exception.AppException;
import com.mars.base.common.utils.web.ResponseResult;
import com.mars.base.web.BaseController;
import com.mars.base.web.model.DataGrid;
import com.mars.manager.user.entity.User;
import com.mars.manager.user.exception.UserBizException;
import com.mars.manager.user.service.UserService;
import com.mars.manager.user.vo.UserVo;

@RestController
@RequestMapping("/user")
public class UserController extends BaseController {

	@Autowired
	private UserService service;

	@PostMapping(value = "/add")
	public Object add(User entity) {
		if (null != this.service.checkValue("username", entity.getUsername())) {
			return ResponseResult.build(false, String.format(UserBizException.USERNAME_EXITS, entity.getUsername()));
		}
		if (null != this.service.checkValue("email", entity.getEmail())) {
			return ResponseResult.build(false, String.format(UserBizException.EMAIL_EXITS, entity.getEmail()));
		}
		if (null != this.service.checkValue("mobile", entity.getMobile())) {
			return ResponseResult.build(false, String.format(UserBizException.MOBILE_EXITS, entity.getMobile()));
		}
		try {
			this.service.insertSelective(entity);
		} catch (UserBizException e) {
			return ResponseResult.addFailed();
		}
		return ResponseResult.addOk();
	}

	@GetMapping(value = "/delete/{ids}")
	public Object delete(@PathVariable String ids) {
		try {
			this.service.deleteByIds(ids);
		} catch (UserBizException e) {
			return ResponseResult.deleteFailed();
		}
		return ResponseResult.deleteOk();
	}

	@PostMapping(value = "/update")
	public Object update(User entity) {
		try {
			User oldUser = this.service.selectById(entity.getId()) ;
			if(null != oldUser.getUsername() && !oldUser.getUsername().equals(entity.getUsername())) {
				if(null != this.service.checkValue("username", entity.getUsername())) {
					return ResponseResult.build(false, String.format(UserBizException.USERNAME_EXITS, entity.getUsername()));
				}
			}
			if(null != oldUser.getEmail() && !oldUser.getEmail().equals(entity.getEmail())) {
				if(null != this.service.checkValue("email", entity.getEmail())) {
					return ResponseResult.build(false, String.format(UserBizException.EMAIL_EXITS, entity.getEmail()));
				}
			}
			if(null != oldUser.getMobile() && !oldUser.getMobile().equals(entity.getMobile())) {
				if(null != this.service.checkValue("mobile", entity.getMobile())) {
					return ResponseResult.build(false, String.format(UserBizException.MOBILE_EXITS, entity.getMobile()));
				}
			}
			this.service.updateSelective(entity);
		} catch (UserBizException e) {
			return ResponseResult.updateFailed();
		}
		return ResponseResult.updateOk();
	}

	@GetMapping(value = "/get/{id}")
	public User get(@PathVariable Long id) {
		return this.service.selectById(id);
	}

	@GetMapping(value = "/list")
	public Object list(UserVo userVo) {
		try {
			PageInfo<User> selectPage = this.service.selectPage(getPageParam(), userVo);
			
			DataGrid<User> dg = new DataGrid<User>() ;
			dg.setRows(selectPage.getList());
			dg.setTotal(selectPage.getTotal());
			return dg ;
		} catch (AppException e) {
			return ResponseResult.loadFailed();
		}
	}
	
	/**
	 * 根据用户帐号获取用户对象
	 * @param account 帐号（用户名/手机号码/邮箱地址）
	 * @return
	 */
	@GetMapping(value = "/getUserByAccount")
	public Object getUserByAccount(String account) {
		try {
			return this.service.getAccount(account) ;
		} catch (AppException e) {
			return ResponseResult.failure();
		}
	}
	
	/**
	 * 锁定或解锁帐号
	 * @param ids
	 * @return
	 */
	@PostMapping(value = "/updateAccountStatus")
	public Object updateAccountStatus(Long[] ids, Integer status) {
		try {
			Integer updateAccountStatus = this.service.updateAccountStatus(ids, status) ;
			if(updateAccountStatus > 0) {
				if(status == 1) {
					return ResponseResult.build(true, "解锁成功") ;
				} else {
					return ResponseResult.build(true, "锁定成功") ;
				}
			} else {
				return ResponseResult.failure() ;
			}
		} catch (AppException e) {
			return ResponseResult.failure() ;
		}
	}
	
	/**
	 * 重置密码
	 * @param ids
	 * @return
	 */
	@PostMapping(value = "/resetPassword")
	public Object resetPassword(Long[] ids) {
		try {
			return this.service.resetPassword(ids) ;
		} catch (AppException e) {
			return ResponseResult.failure() ;
		}
	}
	
	/**
	 * 登录验证
	 * @param account
	 * @param password
	 * @return
	 */
	@PostMapping(value = "/validateLogin")
	public Object validateLogin(String account, String password, HttpServletRequest request, HttpServletResponse response) {
		try {
			
			User user = this.service.getAccount(account) ;
			if(null != user) {
				boolean validatePassword = this.service.validatePassword(user.getPassword(), password, user.getSalt()) ;
				if(validatePassword) {
					if(user.getStatus() == 2) {
						return ResponseResult.build(false, "该帐号已被禁用，请联系管理员") ;
					}
					
					return ResponseResult.build(true, "登录成功", user) ;
				} else {
					return ResponseResult.build(false, "密码错误") ;
				}
				
			} else {
				return ResponseResult.build(false, "用户不存在") ;
			}
			
		} catch (AppException e) {
			return ResponseResult.build(false, "登录发生异常，请联系管理员") ;
		}
	}

}
